package com.lib.net

import android.net.ParseException
import com.google.gson.JsonParseException
import com.lib.base.data.http.ApiException
import com.lib.base.data.http.HttpCode
import com.lib.base.data.http.ServerException
import com.lib.base.utils.LogUtils
import org.json.JSONException
import retrofit2.HttpException
import timber.log.Timber
import java.net.ConnectException
import java.net.SocketTimeoutException

object ApiExceptionService {
    fun handleException(e: Throwable): ApiException {
        val ex: ApiException
        if (e is HttpException) {
            ex = when (e.code()) {
                HttpCode.UNAUTHORIZED.value -> ApiException(e, HttpCode.UNAUTHORIZED)
                else -> ApiException(e, HttpCode.HTTP_ERROR)
            }
        } else if (e is ServerException) {
            // 服务器定义的错误
            ex = when (e.code) {
                HttpCode.UNAUTHORIZED.value -> ApiException(e, HttpCode.UNAUTHORIZED)
                HttpCode.NOT_FOUND.value -> ApiException(e, HttpCode.NOT_FOUND)
                HttpCode.RESULT_NULL.value -> ApiException(e, HttpCode.RESULT_NULL)
                else -> ApiException(e, HttpCode.HTTP_ERROR)
            }
            LogUtils.e("服务器异常", "$e")
        } else if (e is JsonParseException
            || e is JSONException
            || e is ParseException
        ) {
            // 均视为解析错误
            ex = ApiException(e, HttpCode.PARSE_ERROR)
            LogUtils.e("数据解析异常", "$e")
        } else if (e is ConnectException) {
            // 均视为网络错误
            ex = ApiException(e, HttpCode.NETWORK_ERROR)
            LogUtils.e("网络连接失败", "$e")
        } else if (e is SocketTimeoutException) {
            // 访问超时
            ex = ApiException(e, HttpCode.BACK_ERROR)

            LogUtils.e("服务器超时", "$e")
        } else if (e is NullPointerException) {
            ex = ApiException(e, HttpCode.NETWORK_ERROR)

            LogUtils.e("空指针异常，访问路径对么", "$e")
        } else {
            ex = ApiException(e, HttpCode.UNKNOWN)
            LogUtils.e("未知异常", "$e")
        }

        return ex
    }
}